package foxandrabbit;

import java.util.ArrayList;

import javax.swing.JFrame;

import animal.Animal;
import animal.Fox;
import animal.Rabbit;
import cell.Cell;
import field.Field;
import field.Location;
import field.View;

public class FoxAndRabbit {

	private Field theField093121121;
	private View theView093121121;

	public FoxAndRabbit(int size){
		theField093121121 = new Field(size, size);
		for(int col=0;col<theField093121121.getWidth093121121();col++)
			for(int row=0;row<theField093121121.getHeight093121121();row++){
				double probability = Math.random();
				if(probability<0.05){
					theField093121121.place(row, col, new Fox());
				}else if(probability<0.15){
					theField093121121.place(row, col, new Rabbit());
				}
			}

		theView093121121 = new View(theField093121121);
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setTitle("zheshibiaoti");
		frame.add(theView093121121);
		frame.pack();
		frame.setVisible(true);
	}

	public void start(int steps){
		for(int i=0;i<steps;i++){
			step();
			theView093121121.repaint();
			try{
				Thread.sleep(200);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}

	public void step(){
		for(int col=0;col<theField093121121.getWidth093121121();col++)
			for(int row=0;row<theField093121121.getHeight093121121();row++){
				Cell cell = theField093121121.get(row, col);
				if(cell != null){
					Animal animal = (Animal)cell;
					animal.grow();
					if(animal.isAlive()){
						Location loc = animal.move(theField093121121.getFreeNeighbour(row, col));
						if(loc != null){
							theField093121121.move(row, col, loc);
						}
						Cell[] neighbour = theField093121121.getNeighbour(row, col);
						ArrayList<Animal> listRabbit = new ArrayList<Animal>();
						for(Cell an : neighbour){
							if(an instanceof Rabbit){
								listRabbit.add((Rabbit)an);
							}
						}
						if(!listRabbit.isEmpty()){
							Animal fed = animal.feed(listRabbit);
							if(fed != null){
								theField093121121.remove((Cell)fed);
							}
						}
						Animal baby = animal.breed();
						if(baby != null){
							theField093121121.placeRandomAdj(row, col, (Cell)baby);
						}
					}else{
						theField093121121.remove(row, col);
					}
				}
			}
	}

	public static void main(String[] args) {
		FoxAndRabbit fnr = new FoxAndRabbit(30);
		fnr.start(100);
	}
}
